package com.yonyou.gmcc.gateway.wechat.common;

import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.yonyou.gmcc.gateway.wechat.entity.ReceiveXmlEntity;
import com.yonyou.gmcc.gateway.wechat.entity.item;
/**
 * xml与文本消息转换
 * 
 * 
 */
public class ReceiveXmlProcess {

	/**
	 * xml转文本
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> xml2map(HttpServletRequest req)
			throws Exception {
		Map<String, String> map = new HashMap<>();
		SAXReader reader = new SAXReader();

		InputStream is = req.getInputStream();
		Document doc = reader.read(is);

		Element root = doc.getRootElement();

		List<Element> elements = root.elements();

		for (Element e : elements) {
			map.put(e.getName(), e.getText());
		}
		is.close();

		return map;
	}

	/**
	 * 微信消息转xml
	 * 
	 * @param message
	 * @return
	 */
	public static String text2xml(ReceiveXmlEntity message) {
		xstream.alias("xml", message.getClass());
		xstream.alias("item", new item().getClass());
		return xstream.toXML(message);
	}

	private static XStream xstream = new XStream(new XppDriver() {

		@Override
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				@Override
				@SuppressWarnings("rawtypes")
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				@Override
				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}

	});

}
